#!/bin/bash

db_name="zentyal"
db_user="zentyal"

create_db()
{
    PASSWD_FILE='/var/lib/zentyal/conf/zentyal-mysql.passwd'

    # Restart mysql so it loads the zentyal.cnf file
    service mysql restart

    # Do not disable innodb if there are other databases previous to the
    # creation of the Zentyal one
    lines=$(echo "show databases" | mysql --defaults-file=/etc/mysql/debian.cnf | wc -l)
    if [ $lines -gt 4 ]
    then
        sed -i 's/innodb = off/innodb = on/' /etc/mysql/conf.d/zentyal.cnf
    fi

    # If password file exists, but login is incorrect
    # Delete password file and database user, so we create them again
    if [ -s $PASSWD_FILE ]
    then
        PASSWD=`cat $PASSWD_FILE`
        if ! mysql -u$db_user -p$PASSWD -e 'exit' > /dev/null 2>&1; then
            mysql --defaults-file=/etc/mysql/debian.cnf -e "DROP USER '$db_user'@'localhost'"
            rm -rf $PASSWD_FILE
        fi
    fi

    # If there is no password file, create a new one
    if [ -s $PASSWD_FILE ]
    then
        PASSWD=`cat $PASSWD_FILE`
    else
        PASSWD=`tr -dc A-Za-z0-9 < /dev/urandom | head -c8`
        echo -n $PASSWD > $PASSWD_FILE
        chmod 400 $PASSWD_FILE
    fi

    # Create zentyal database and populate it
    # Also create zentyal user (and change root password so it has the zentyal one)
    echo "Creating the $db_name database"
    echo "CREATE DATABASE $db_name CHARACTER SET utf8 COLLATE utf8_unicode_ci;" | mysql --defaults-file=/etc/mysql/debian.cnf
    echo "CREATE USER '$db_user'@'localhost' IDENTIFIED BY \"$PASSWD\";"  | mysql --defaults-file=/etc/mysql/debian.cnf
    echo "GRANT ALL ON $db_name.* TO '$db_user'@'localhost';"  | mysql --defaults-file=/etc/mysql/debian.cnf
    echo "UPDATE mysql.user SET authentication_string=('$PASSWD') WHERE user='root';" | mysql --defaults-file=/etc/mysql/debian.cnf    
    echo "FLUSH PRIVILEGES;" | mysql --defaults-file=/etc/mysql/debian.cnf

    perl -MEBox -MEBox::Util::SQL -e'EBox::init(); EBox::Util::SQL::createCoreTables(); 1';
}

if ! [ -d /var/lib/mysql/$db_name ]; then
    create_db
    touch /var/lib/zentyal/.db-created
fi

